{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "列表的特点：\n",
    "1. 列表是 mutable 对象，我们可以修改其内容。\n",
    "2. 列表的切片操作返回一个包含所请求元素的新列表。这意味着切片操作会返回列表的一个浅拷贝。如果希望获得一个深拷贝，需要调用 list 的 copy 方法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "ls = [1, 2, 3]\n",
    "\n",
    "ls1 = ls[1:2]  # 切片是原列表的一个浅拷贝 对其修改的结果会直接反映到ls本身\n",
    "ls2 = ls[1:2].copy()  # 原列表的一个深拷贝 现修改ls2对ls无影响"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ls1 = [0,0,0]\n",
    "ls"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ls: [1, 2, 3]\n",
      "ls2: [0, 0, 0]\n"
     ]
    }
   ],
   "source": [
    "ls2 = [0,0,0]\n",
    "print('ls:', ls)\n",
    "print('ls2:', ls2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**最佳实践**：在遍历同一个可迭代对象（下面例子中是字典）时修改该可迭代对象的代码可能很难获得正确的结果。通常，更直接的做法是循环遍历该可迭代对象的副本或创建新集合："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'hu': 'active'}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "users = {\n",
    "    'li' : 'inactive',\n",
    "    'hu' : 'active',\n",
    "    'liu' : 'inactive',\n",
    "}\n",
    "\n",
    "# Strategy: Iterate over a copy \n",
    "for user, status in users.copy().items(): \n",
    "    if status == 'inactive':\n",
    "        del users[user]\n",
    "\n",
    "users"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为列表添加元素有两种方法（下面分别给出实例）：\n",
    "1. 使用 + 号\n",
    "2. 使用 list 的 append 方法（更推荐，效率更高，但一次只能添加一个对象）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4]\n",
      "[1, 2, 3, 4, 0]\n"
     ]
    }
   ],
   "source": [
    "ls = [1, 2]\n",
    "# 1\n",
    "ls = ls + [3, 4]\n",
    "print(ls)\n",
    "\n",
    "# 2 \n",
    "ls.append(0)\n",
    "print(ls)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
